﻿using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Utils;

namespace RhotCMS.AdditionalCode
{
    public class LinksHrefRewriter
    {
        public string AddPreview(string html)
        {
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);
            var aTag = doc.DocumentNode.SelectNodes("//a[@href]");
            if (aTag == null) return html;
            foreach (HtmlNode link in aTag)
            {

                HtmlAgilityPack.HtmlAttribute att = link.Attributes.SingleOrDefault(x => x.Name == "href");
                att.Value = FixLink(att.Value);
            }

            var imgTag = doc.DocumentNode.SelectSingleNode("//div[@id=\"previewversion\"]");

            HtmlNode previewImg = new HtmlNode(HtmlNodeType.Element, doc, 0);

            if (imgTag == null)
                return doc.DocumentNode.OuterHtml;

            previewImg.Name = "img";
            previewImg.Attributes.Add("src", URLUtils.GetAbsVirtualAppPath() + "Content/img/previewversion.gif");

            imgTag.ChildNodes.Add(previewImg);

            return doc.DocumentNode.OuterHtml;
        }

        private string FixLink(string att)
        {
            if (att.Contains("preview") || att.Contains("#") || att == URLUtils.GetAbsVirtualAppPath())
                return att;

            if (att.Contains(URLUtils.GetAbsVirtualAppPath()))
            {
                if (!att.Contains("?"))
                    att += "?preview";
                else
                    att += "&preview";
            }

            if (!att.Contains("http") && !att.Contains("www"))
            {
                if (!att.Contains("?"))
                    att += "?preview";
                else
                    att += "&preview";
            }

            return att;
        }
    }
}